/* eslint-disable */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Spin, Row, Col, Modal } from 'antd';
import { CaretRightOutlined, CaretDownOutlined } from '@ant-design/icons';
import _ from 'lodash';
import { PrimaryC, PrimaryGhostC, FirstHeaderC, SecondHeaderC, TableC, FixedButtonC } from '@/src/components';
import { renderChinese, titleObj, tradersCol, rateCol, controllingShareholderCol, otherShareholderCol, beneficiaryCol, representativeCol } from './columnsData';

import FormRenderC from './formRender';
import ModalRenderC from './modalRender';

import style from './index.less';
import { isZiGuanEvir } from '@/src/utils/commonFunc';

const { confirm } = Modal;
class Counterparties extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      modalType: '', // 模态框显示那种form表单
      title: '', // 模态框名称
      counterpartiesID: '', // 当前交易对手id
      isExpand0: true, // 控股股东 是否展开
      isExpand1: true, // 其他股东 是否展开
      isExpand2: true, // 实际受益人 是否展开
      isExpand3: true, // 法定代表人 是否展开
      tempObj: {
        traders: JSON.parse(JSON.stringify(tradersCol)),
        rate: JSON.parse(JSON.stringify(rateCol)),
        controllingShareholder: JSON.parse(JSON.stringify(controllingShareholderCol)),
        otherShareholder: JSON.parse(JSON.stringify(otherShareholderCol)),
        beneficiary: JSON.parse(JSON.stringify(beneficiaryCol)),
        representative: JSON.parse(JSON.stringify(representativeCol)),
      },
      timeStamp: undefined, // 时间戳
      params: {
        // 页面参数对象
        counterparties: {
          basicInfo: {
            // 基础信息
            shortName: '', // 交易对手短名
            longName: '', // 交易对手长名
            role: [], // 交易对手角色
            isProduct: '', // 是否为产品
            parentOrg: '', // 母机构
            countries: '', // 国家地区
            needApproval: '', // 是否需要审批
            timeOfExpiration: '', // 失效时间
            status: '', // 可用状态
            creator: '', // 创建人
            timeOfCreation: '', // 创建时间
            modifer: '', // 上一次更改人
            timeOfLastModification: '', // 上一次更改时间
          },
          rate: {
            // 交易对手评级
            dataSource: [],
            columns: [],
            pageInfo: {},
          },
          traders: {
            // 对手交易员信息
            dataSource: [],
            columns: [],
            pageInfo: {},
          },
          attribute: {
            // 交易对手属性(对手方)
            interBankAccount: '', // 银行间账户名称
            newFourCategories: '', // 是否新四类
            seatNumber: '', // 大宗平台交易所席位
            nafmii: '', // 是否签署NAFMII协议
            institutionalTrader: '', // 机构交易员代码(前三位)
            counterpartyType: '', // 交易对手类型
            issuerScale: '', // 发行机构类型（按规模划分）
            issuerField: '', // 发行机构类型（按技术领域划分）
            issuerEconomy: '', // 发行机构类型（按经济类型划分）
            issuerIndustry: '', // 发行机构所属行业
            issuerRemark: '', // 备注
          },
        },
        organ: {
          // 机构信息
          basicInfo: {
            // 无
            creditCode: '', // 社会统一信用代码
            business: '', // 经营范围
            domicile: '', // 住所
            contact: '', // 联系方式
          },
          controllingShareholder: {
            // 控股股东信息
            dataSource: [],
            columns: [],
            pageInfo: {},
          },
          otherShareholder: {
            // 其他股东信息
            dataSource: [],
            columns: [],
            pageInfo: {},
          },
          beneficiary: {
            // 实际受益人信息
            dataSource: [],
            columns: [],
            pageInfo: {},
          },
          representative: {
            // 法定代表人
            dataSource: [],
            columns: [],
            pageInfo: {},
          },
        },
      },
      resetParams: {}, // 原始参数
      visible: false, // 模态框默认显示
      parentOrgList: [], // 母机构列表
      parentOrgListSelect: [], // 母机构过滤掉自己的列表
      isZiguan: false, // 是否资管环境 默认maat
      isIssuer: false, // 发行方
      isCounterparty: false, // 对手方
      // 国家地区
      countryStatus: '',
    };
  }

  componentDidMount() {
    const { params } = this.state;
    this.setState({
      resetParams: _.cloneDeep(params),
    });
    const { type } = this.props;
    const approvalId = this.props.id; // props.id 只有审批页面传入
    let ziguanObj;
    if (isZiGuanEvir()) {
      ziguanObj = isZiGuanEvir();
      this.setState({
        isZiguan: true,
        ziGuanKey: ziguanObj.ziGuanKey, // 保存url里的时间戳
      });
    }
    // 资管环境下取url中的交易对手id ;maat环境下取storage中的id 编辑的时候
    const id_edit = ziguanObj && ziguanObj.counterpartiesID ? ziguanObj.counterpartiesID : sessionStorage.getItem('counterpartiesID_edit');

    if (approvalId && type == 'query') {
      // 审批查询的时候 实时调用
      this.setState({
        timeStamp: this.props.timeStamp,
      });
      return;
    }
    if (!approvalId) {
      // 非审批状态下获取母机构
      this.getParentOrgList(type == 'edit' ? id_edit : '1');
    }
    if (type == 'query') {
      // 获取id查询详情页
      sessionStorage.removeItem('isQueryUpdate'); // 首次进入清空详情更新的标志位，避免componentWillReceiveProps里再次请求
      // 资管环境下取url中的交易对手id ;maat环境下取storage中的id 查询的时候
      const id = ziguanObj && ziguanObj.counterpartiesID ? ziguanObj.counterpartiesID : sessionStorage.getItem('counterpartiesID');
      if (id) {
        this.setState(
          {
            counterpartiesID: approvalId || id,
          },
          () => {
            this.queryData();
          },
        );
      }
    } else if (type == 'edit') {
      if (id_edit) {
        this.setState(
          {
            counterpartiesID: id_edit,
          },
          () => {
            this.queryData();
          },
        );
      }
      if (approvalId) {
        // 审批 编辑状态
        this.queryData();
      }
    }
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    const { type } = this.props;
    if (type == 'query') {
      // 若是query状态，在componentWillReceiveProps函数中，若当前state中counterpartiesID不等于sessionstorage中获取counterpartiesID值，则调用接口，获取新的交易对手详情，进行展示；
      // maat环境下详情的更新
      const id = sessionStorage.getItem('counterpartiesID');
      const isQueryUpdate = sessionStorage.getItem('isQueryUpdate');
      sessionStorage.removeItem('isQueryUpdate'); // 清空标志位
      if (isQueryUpdate && this.state.counterpartiesID) {
        // 初始化在didmount里完成，避免重复请求这里做个判断 有交易对手id之后才能请求 详情页面进行更新，编辑页面必须关闭重新打开，不会进入到该方法
        this.setState(
          {
            counterpartiesID: id,
          },
          () => {
            this.queryData();
          },
        );
      }
    }
    if (this.state.timeStamp !== this.props.timeStamp && type == 'query') {
      // 审批状态下
      this.setState(
        {
          counterpartiesID: this.props.id,
          timeStamp: this.props.timeStamp,
        },
        () => {
          this.queryData();
        },
      );
    }
  }

  // 获取母机构
  getParentOrgList(id) {
    this.props.dispatch({
      // 获取母机构
      type: 'counterpartyInformationM/getParentOrgList',
      payload: {
        id,
      },
      callback: (params, type) => {
        if (type == 'success') {
          this.setState({
            ...params,
          });
        } else {
          this.setState({
            parentOrgList: [], // 母机构列表
            parentOrgListSelect: [], // 母机构过滤掉自己的列表
          });
        }
      },
    });
  }

  // 查询详情数据
  queryData = () => {
    const { counterpartiesID } = this.state;
    const queryParams = this.props.id // 判断是否审批页面
      ? {
          approval: true,
          id: this.props.id,
          type: this.props.type,
        }
      : {
          id: counterpartiesID,
          type: this.props.type,
        };
    this.props.dispatch({
      type: 'counterpartyInformationM/getBasicDetail',
      payload: {
        ...queryParams,
      },
      callback: (params, type) => {
        if (type == 'success') {
          if (this.props.type == 'edit') {
            this.roleChange(params?.params?.counterparties?.basicInfo?.role?.includes('1'), params?.params?.counterparties?.basicInfo?.role?.includes('1'));
          }
          if (params) {
            this.setState(
              {
                ...params,
                countryStatus: params?.params?.counterparties?.basicInfo?.countries,
                info: params.params,
              },
              () => {
                if (this.props.id) this.getParentOrgList(this.state.params.counterpartyBasicInfoId); // 获取母机构
              },
            );
          }
        } else {
          // 失败 重置数据
          this.setState({
            params: _.cloneDeep(this.state.resetParams),
          });
        }
      },
    });
  };

  deleteRowData = (id, type) => {
    // 删除某一列
    const { params } = this.state;
    if (type == 'traders' || type == 'rate') {
      const arr = params.counterparties[type].dataSource || [];
      params.counterparties[type].dataSource = [...arr.filter((item) => item.key != id)];
    } else {
      const arr = params.organ[type].dataSource || [];
      params.organ[type].dataSource = [...arr.filter((item) => item.key != id)];
    }
    this.setState({
      params: { ...params },
    });
  };

  submit = async () => {
    // 编辑和新增
    const { dispatch, type } = this.props;
    const { params, isCounterparty, isIssuer } = this.state;
    // //获取对手属性form表单
    await this.basicInfoRef.getFormData();
    await this.organRef.getFormData();
    if (isCounterparty) await this.attrRef.getFormData();
    if (isIssuer) await this.issuer.getFormData();

    // 判断是否校验通过 通过则请求后台
    // 当选择：交易对手属性（对手方）
    if (isCounterparty) {
      if (sessionStorage.getItem('attr')) {
        sessionStorage.removeItem('attr');
      } else {
        return;
      }
    }
    // 当选择：交易对手属性（发行人）
    if (isIssuer) {
      if (sessionStorage.getItem('issuer')) {
        sessionStorage.removeItem('issuer');
      } else {
        return;
      }
    }
    if (sessionStorage.getItem('basic') && sessionStorage.getItem('organ')) {
      sessionStorage.removeItem('basic');
      sessionStorage.removeItem('organ');
      if (this.props.id) {
        // 审批页面加一个入参 不进行页面跳转 判断请求审批接口还是交易对手接口
        params.tempId = this.props.id;
      }
      for (const key in params) {
        const item = params[key];
        if (typeof item === 'object') {
          for (const indexKey in item) {
            const itemChild = item[indexKey];
            if (itemChild.columns) itemChild.columns = [];
          }
        }
      }
      dispatch({
        type: 'counterpartyInformationM/saveOrUpdateBasic',
        payload: {
          ...params,
          type,
        },
        callback: () => {
          if (this.props.id) {
            // 审批页面调用
            this.props.onCancel();
          } else {
            if (this.state.isZiguan) {
              // 资管平台 跳转处理
              if (type == 'add') {
                // 当前新增页面 通知iframe 更新或者打开列表页iframe
                const obj = { isUpdateFlag: true };
                window.parent.postMessage(obj, '*'); // 抛出事件，将数据转成字符串避免一些浏览器不兼容
              } else {
                // 当前编辑页面 通知iframe 更新或者打开详情页iframe
                const obj = { counterpartiesID: this.state.counterpartiesID, ziGuanKey: new Date().getTime() };
                window.parent.postMessage(obj, '*'); // 抛出事件，将数据转成字符串避免一些浏览器不兼容
              }
              return;
            }
            if (type == 'add') {
              // 当前是新增页面 则跳转至列表页
              sessionStorage.setItem('isUpdateFlag', 1); // 是否需要更新交易对手列表
              dispatch({
                // 跳转至列表页
                type: 'tabController/closeTab',
                payload: {
                  newUrl: '/counterpartyManagement/counterpartyInformation',
                },
              });
            } else {
              // 当前是编辑页面 则跳转至详情页
              sessionStorage.setItem('counterpartiesID', this.state.counterpartiesID); // 是否需要更新详情页
              sessionStorage.removeItem('counterpartiesID_edit');
              sessionStorage.setItem('isQueryUpdate', 1); // 更新详情页
              dispatch({
                // 跳转至列表页
                type: 'tabController/closeTab',
                payload: {
                  newUrl: '/counterpartyManagement/counterpartyInfoQuery',
                },
              });
            }
          }
        },
      });
    }
  };

  // 打开模态框
  addTableData = (type) => {
    this.setState({
      modalType: type,
      title: titleObj[type],
      visible: true,
    });
  };

  onCancel = () => {
    // 点击取消按钮 关闭页面
    confirm({
      title: '确认取消吗?',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        if (this.props.id) {
          // 审批页面调用
          this.props.onCancel();
          return;
        }
        if (this.state.isZiguan) {
          // 如果是资管环境 则通知iframe跳转至列表页
          const obj = { isUpdateFlag: false };
          window.parent.postMessage(obj, '*'); // 抛出事件，将数据转成字符串避免一些浏览器不兼容
          return;
        }
        // 跳转回列表页
        this.props.dispatch({
          type: 'tabController/closeTab',
          payload: {
            newUrl: '/counterpartyManagement/counterpartyInformation',
          },
        });
      },
    });
  };

  handleExpand = (type) => {
    // 是否展开状态切换
    this.setState({
      [type]: !this.state[type],
    });
  };

  roleChange = (isCounterparty, isIssuer) => {
    this.setState({
      isCounterparty,
      isIssuer,
    });
  };

  // 改变国家地区
  changeCountryStatus = (countryStatus) => {
    this.setState({
      ...countryStatus,
    });
  };

  render() {
    const { modalType, title, isExpand0, isExpand1, isExpand2, isExpand3, tempObj, countryStatus } = this.state;
    const {
      loading,
      globalM: {
        dataDictionary: { COUNTER_PARTY_RATE_ORGAN, COUNTER_PARTY_CERTIFICATE_TYPE, COUNTER_PARTY_RATE_TYPE },
      },
    } = this.props;
    const { type } = this.props;
    const { params, isCounterparty, isIssuer } = this.state;
    const {
      counterparties: { traders, rate, basicInfo, attribute },
      organ: { controllingShareholder, otherShareholder, beneficiary, representative, basicInfo: organBasic },
    } = params;
    for (var key in tempObj) {
      if (key == 'rate') {
        tempObj[key].map((item) => {
          if (item.key == 'ratingAgency' || item.key == 'ratingType') {
            item.render = (text) => {
              return <span>{item.key == 'ratingAgency' ? renderChinese(text, COUNTER_PARTY_RATE_ORGAN) : renderChinese(text, COUNTER_PARTY_RATE_TYPE)}</span>;
            };
          }
        });
      }
      if (key != 'rate' && key != 'traders') {
        tempObj[key].map((item) => {
          if (item.key == 'certificateType') {
            item.render = (text) => {
              return <span>{renderChinese(text, COUNTER_PARTY_CERTIFICATE_TYPE)}</span>;
            };
          }
        });
      }
      // 判断是否需要添加操作列
      const temp = key;
      if (tempObj[key][tempObj[key].length - 1].key == 'operate') {
        if (type == 'query') {
          tempObj[key].pop();
        }
      } else if (type != 'query') {
        tempObj[key].push({
          title: '操作',
          key: 'operate',
          width: 100,
          type: 'operate',
          operates: [
            {
              title: '删除',
              onClick: (record, index) => this.deleteRowData(record.key, temp),
            },
          ],
        });
      }

      tempObj[key].map((item, index) => {
        if (tempObj[key].length - 1 != index || index != 0) {
          item.width = `${parseFloat(100 / tempObj[key].length - 2)}%`;
        }
      });
    }
    const content = (
      <>
        <FirstHeaderC title='交易对手详情' />
        <div className={type == 'query' ? 'main_bg main_bg1' : ''}>
          <FormRenderC
            infos={this.state.info}
            status={type}
            changeCountryStatus={this.changeCountryStatus}
            onRef={(ref) => (this.basicInfoRef = ref)}
            type='basic'
            countryStatus={countryStatus}
            info={basicInfo}
            that={this}
            roleChange={this.roleChange}
          />
        </div>
        <div className={type == 'query' ? 'main_bg' : ''}>
          <FormRenderC status={type} onRef={(ref) => (this.statusRef = ref)} type='status' countryStatus={countryStatus} info={basicInfo} that={this} />
        </div>
        {isCounterparty ? (
          <Row>
            <SecondHeaderC title='交易对手属性（对手方）' />
            <div className={type == 'query' ? 'main_bg' : ''} style={{ width: '100%' }}>
              <FormRenderC status={type} onRef={(ref) => (this.attrRef = ref)} type='attr' countryStatus={countryStatus} info={attribute} that={this} />
            </div>
          </Row>
        ) : null}
        {isIssuer ? (
          <Row>
            <SecondHeaderC title='交易对手属性（发行人）' />
            <div className={type == 'query' ? 'main_bg' : ''} style={{ width: '100%' }}>
              <FormRenderC status={type} onRef={(ref) => (this.issuer = ref)} type='issuer' countryStatus={countryStatus} info={attribute} that={this} />
            </div>
          </Row>
        ) : null}
        <Row>
          <Col span={12}>
            <div className={style.sec_title}>
              <SecondHeaderC
                title='对手交易员信息'
                Right={
                  type != 'query' ? (
                    <PrimaryC
                      style={{ position: 'absolute', right: 0, top: 0 }}
                      onClick={() => {
                        this.addTableData('traders');
                      }}
                      title='新增'
                    />
                  ) : null
                }
              />
            </div>
            <div className='tablebg'>
              <TableC
                columns={tempObj.traders}
                dataSource={traders.dataSource || []}
                hidePage={true}
                rowKey='key'
                scroll={traders.dataSource && traders.dataSource.length > 4 ? { x: '100%', y: 120 } : {}}
              />
            </div>
          </Col>
          <Col span={12}>
            <div className={style.sec_title}>
              <SecondHeaderC
                title='交易对手评级'
                Right={
                  type != 'query' ? (
                    <PrimaryC
                      style={{ position: 'absolute', right: 0, top: 0 }}
                      onClick={() => {
                        this.addTableData('rate');
                      }}
                      title='新增'
                    />
                  ) : null
                }
              />
            </div>
            <div className='tablebg'>
              <TableC
                columns={tempObj.rate}
                dataSource={rate.dataSource || []}
                hidePage={true}
                rowKey='key'
                scroll={rate.dataSource && rate.dataSource.length > 4 ? { x: '100%', y: 120 } : {}}
              />
            </div>
          </Col>
        </Row>
        <FirstHeaderC title='机构信息' />
        <div className={type == 'query' ? 'main_bg' : ''}>
          <FormRenderC status={type} countryStatus={countryStatus} onRef={(ref) => (this.organRef = ref)} type='organ' info={organBasic} that={this} />
        </div>
        <Row>
          <div className={style.sec_title}>
            <SecondHeaderC
              title='控股股东信息'
              Left={
                isExpand0 ? <CaretDownOutlined onClick={() =>this.handleExpand('isExpand0')} /> : <CaretRightOutlined onClick={() =>this.handleExpand('isExpand0')} />
              }
              Right={
                type != 'query' ? (
                  <PrimaryC
                    style={{ position: 'absolute', right: 0, top: '-6px' }}
                    onClick={() => {
                      this.addTableData('controllingShareholder');
                    }}
                    title='新增'
                  />
                ) : null
              }
            />
          </div>
          {isExpand0 ? (
            <TableC
              columns={tempObj.controllingShareholder}
              dataSource={controllingShareholder.dataSource || []}
              hidePage={true}
              rowKey='key'
              scroll={controllingShareholder.dataSource && controllingShareholder.dataSource.length > 4 ? { x: '100%', y: 120 } : {}}
            />
          ) : null}
        </Row>
        <Row>
          <div className={style.sec_title}>
            <SecondHeaderC
              title='其他股东信息'
              Left={
                isExpand1 ? <CaretDownOutlined onClick={() =>this.handleExpand('isExpand1')} /> : <CaretRightOutlined onClick={() =>this.handleExpand('isExpand1')} />
              }
              Right={
                type != 'query' ? (
                  <PrimaryC
                    style={{ position: 'absolute', right: 0, top: '-6px' }}
                    onClick={() => {
                      this.addTableData('otherShareholder');
                    }}
                    title='新增'
                  />
                ) : null
              }
            />
          </div>
          {isExpand1 ? (
            <TableC
              columns={tempObj.otherShareholder}
              dataSource={otherShareholder.dataSource || []}
              hidePage={true}
              rowKey='key'
              scroll={otherShareholder.dataSource && otherShareholder.dataSource.length > 4 ? { x: '100%', y: 120 } : {}}
            />
          ) : null}
        </Row>
        <Row>
          <div className={style.sec_title}>
            <SecondHeaderC
              title='实际受益人信息'
              Left={
                isExpand2 ? <CaretDownOutlined onClick={() =>this.handleExpand('isExpand2')} /> : <CaretRightOutlined onClick={() =>this.handleExpand('isExpand2')} />
              }
              Right={
                type != 'query' ? (
                  <PrimaryC
                    style={{ position: 'absolute', right: 0, top: 0 }}
                    onClick={() => {
                      this.addTableData('beneficiary');
                    }}
                    title='新增'
                  />
                ) : null
              }
            />
          </div>
          {isExpand2 ? (
            <TableC
              columns={tempObj.beneficiary}
              dataSource={beneficiary.dataSource || []}
              hidePage={true}
              rowKey='key'
              scroll={beneficiary.dataSource && beneficiary.dataSource.length > 4 ? { x: '100%', y: 120 } : {}}
            />
          ) : null}
        </Row>
        <Row>
          <div className={style.sec_title}>
            <SecondHeaderC
              title='法定代表人信息'
              Left={
                isExpand3 ? <CaretDownOutlined onClick={() =>this.handleExpand('isExpand3')} /> : <CaretRightOutlined onClick={() =>this.handleExpand('isExpand3')} />
              }
              Right={
                type != 'query' ? (
                  <PrimaryC
                    style={{ position: 'absolute', right: 0, top: '-6px' }}
                    onClick={() => {
                      this.addTableData('representative');
                    }}
                    title='新增'
                  />
                ) : null
              }
            />
          </div>
          {isExpand3 ? (
            <TableC
              columns={tempObj.representative}
              dataSource={representative.dataSource || []}
              hidePage={true}
              rowKey='key'
              scroll={representative.dataSource && representative.dataSource.length > 4 ? { x: '100%', y: 120 } : {}}
            />
          ) : null}
        </Row>
      </>
    );
    return (
      <div className={style.counterpartyInfoAddConetent}>
        <div className='counterparties'>
          <Spin spinning={loading.effects['counterpartyInformationM/saveOrUpdateBasic'] == true || loading.effects['counterpartyInformationM/getBasicDetail'] == true}>
            {type != 'query' ? (
              <FixedButtonC
                topHtml={content}
                bottomHtml={
                  <div style={{ width: '100%', textAlign: 'right' }}>
                    <PrimaryGhostC title={'取消'} onClick={this.onCancel} style={{ marginRight: '20px' }} />
                    <PrimaryC onClick={this.submit} title='保存' />
                  </div>
                }
              />
            ) : (
              content
            )}
          </Spin>
        </div>
        {type != 'query' ? this.state.visible ? <ModalRenderC visible={this.state.visible} type={modalType} status={type} title={title} that={this} /> : null : null}
      </div>
    );
  }
}

export default connect(({ counterpartyInformationM, globalM, tabController, tradingCompanyM, loading }) => ({
  counterpartyInformationM,
  globalM,
  tabController,
  tradingCompanyM,
  loading,
}))(Counterparties);
